package com.zztest.aitestmini.common;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @Author: zhangcheng
 * @Description: 拦截器示例
 * @Date: 2021/3/24/024 11:28
 * @Version: 1.0
 */
@Component  // 生成 springBean 以便注入
@Slf4j
public class DemoInterceptor  implements HandlerInterceptor {
    @Autowired
    private TokenDb tokenDb;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle===================");
        String requestUri =  request.getRequestURI();
        log.info("request.getURI:请求地址："+requestUri);
        //放开不需要登录校验的接口

        boolean passFlag= false; //标识符
        if (requestUri.contains("/ZzUser/login")
              || requestUri.contains("/ZzUser/register")){
            passFlag=true;
        }
        if(passFlag){
            return true;
        }
        // 1从请求的head 获取客户端附带的token
        String tokenStr = request.getHeader(UserBaseStr.LOGIN_TOKEN);
        // 2 判断请求是否含有token响应码设401，抛出业务异常
        if (StringUtils.isEmpty(tokenStr)){
            response.setStatus(401);
            ServiceException.throwEx("客户端未传入token");
        }
        //3 从tokendb根据 token 查询tokenDto
        if (Objects.isNull(tokenDb.getUserInfo(tokenStr))){
            response.setStatus(401);
            ServiceException.throwEx("用户未登录");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle");
        log.info("request.getURI"+request.getRequestURI());
        response.setCharacterEncoding("utf-8");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion");
        log.info("request.getURI"+request.getRequestURI());
        response.setCharacterEncoding("utf-8"); // 解决乱码

    }
}
